<?php
namespace Back\Model;
use Think\Cache\Driver\Redis;
use Think\Model;
class CategoryModel extends Model{
//开启批量验证

protected $patchValidate=true;

//自动验证
protected $_validate=[
    //自己写规则
];
//填充
protected $_auto=[
    //自己写填充规则

    //仅仅需要在插入维护
    ['created_at','time',self::MODEL_INSERT,'function'],
    //更新时间，插入和更新是都需要更新
    ['updated_at','time',self::MODEL_BOTH,'function'],
];

  public function  getTree(){
      //使用缓存
      S([
          'type'=>'redis',
          //配置中，获取redis服务器的信息
          'host'=>CG('redis_host','127.0.0.1'),
          'port' =>CG('port','6379'),
      ]);

      //从缓存中获取。分类树
      $tree =S('category_tree');
      if(!$tree){
          //没有缓存，执行查询，递归控制结构
          $list =$this->order('sort_number')->select();
          $tree=$this->tree($list);
          //入缓存
          S('category_tree',$tree);
      }
      //返回数据
      return $tree;
  }

  protected function  tree($list,$category_id =0,$deep =0){

      static $tree =[];
      //遍历所有分类
      foreach ($list as $row){
          //是否为子分类
          if($row['parent_id']==$category_id){
              //记录深度
              $row['deep'] =$deep;
              //保存该分类
              $tree[]=$row;
              //递归检索后代分类
              $this->tree($list,$row['category_id'],$deep+1);
          }
      }
      return $tree;
  }
}

